package com.dw.mall.product.service.impl;

import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dw.common.utils.PageUtils;
import com.dw.common.utils.Query;

import com.dw.mall.product.dao.CategoryDao;
import com.dw.mall.product.entity.CategoryEntity;
import com.dw.mall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1.查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);
        //2.组装成父子的树形结构
        //1）先找到所有一级分类  通过过滤器找到parentcid=0的数据（一级分类）收集到List里 stream jdk8新特性
        List<CategoryEntity> level1Menus = entities.stream().filter((categoryEntity) ->
                categoryEntity.getParentCid() == 0
        ).map((menu) -> {
            //当前菜单的子分类保存到children
            menu.setChildren(getChildrens(menu, entities));
            return menu;
        }).sorted((menu1, menu2) -> {
            //排序
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort()  == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());

        return level1Menus;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 1.检查当前删除的菜单是否被别的地方引用

        //逻辑删除：用一个字段作为标识位表示是否被删除 1-未删除 0-已删除
        baseMapper.deleteBatchIds(asList);
    }

    /**
     * 从all 下 找出root 下的 叶子节点
     * @param root 被查寻的元素
     * @param all   所有
     * @return root的子菜单
     */
    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {
        //当前菜单的子分类
        List<CategoryEntity> children = all.stream().filter((categoryEntity) -> {
            //当前元素的parent id 和root id 相同，当前菜单就是root的子菜单
            return categoryEntity.getParentCid().equals(root.getCatId());
        }).map((categoryEntity) -> {
            //继续找到子菜单
            categoryEntity.setChildren(getChildrens(categoryEntity, all));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            //排序
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort()  == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());

        return children;
    }

}